package com.yima.baseproj.module.sys.menu;

import cn.hutool.core.bean.BeanUtil;
import com.yima.baseproj.aop.log.Logging;
import com.yima.baseproj.module.sys.menu.model.MenuAddOrEditModel;
import com.yima.baseproj.config.exception.type.ApiException;
import com.yima.baseproj.module.sys.menu.model.*;
import com.yima.baseproj.module.config.BaseController;
import com.yima.baseproj.module.sys.menu.model.SysMenuAddParamModel;
import com.yima.baseproj.module.sys.menu.model.SysMenuEditParamModel;
import com.yima.baseproj.security.SecurityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author 一码
 * @createDate 2023/4/1 09:00
 * @contact 1424529270@qq.com
 */
@Api(tags = "菜单管理")
@RestController
@RequestMapping("/api/sys/menu")
public class SysMenuController extends BaseController {

    @Autowired
    private SysMenuService sysMenuService;

    @PreAuthorize("hasAuthority('sys:menu:findAllByTree')")
    @ApiOperation("查询树形列表")
    @GetMapping("/findAllByTree")
    public Object findAllByTree(){
        List<SysMenuEntity> menuAllList = sysMenuService.list();
        List<MenuAddOrEditModel> list = BeanUtil.copyToList(menuAllList, MenuAddOrEditModel.class);
        List<MenuAddOrEditModel> caidanList = list.stream().filter(item->"0".equals(item.getPid())).sorted(Comparator.comparing(MenuAddOrEditModel::getSort)).collect(Collectors.toList());
        for (MenuAddOrEditModel caidanModel : caidanList) {
            List<MenuAddOrEditModel> zicaidanList = list.stream().filter(item->caidanModel.getId().equals(item.getPid())).sorted(Comparator.comparing(MenuAddOrEditModel::getSort)).collect(Collectors.toList());
            for (MenuAddOrEditModel zicaidanModel : zicaidanList) {
                List<MenuAddOrEditModel> gongnengList = list.stream().filter(item->zicaidanModel.getId().equals(item.getPid())).sorted(Comparator.comparing(MenuAddOrEditModel::getSort)).collect(Collectors.toList());
                zicaidanModel.setChildren(gongnengList);
            }
            caidanModel.setChildren(zicaidanList);
        }
        return caidanList;
    }

    @Logging(tags = "菜单管理",value = "添加")
    @PreAuthorize("hasAuthority('sys:menu:add')")
    @ApiOperation("添加")
    @PostMapping("/add")
    public void addMenu(@Validated @RequestBody SysMenuAddParamModel paramModel){
        SysMenuEntity sysMenuEntity = new SysMenuEntity();
        sysMenuEntity.setSysMenuEntity(paramModel);
        sysMenuService.save(sysMenuEntity);
        String levelStr = sysMenuService.getMenuLevelStr(paramModel.getPid(),sysMenuEntity.getId());
        sysMenuEntity.setLevelStr(levelStr);
        sysMenuService.updateById(sysMenuEntity);
    }

    @Logging(tags = "菜单管理",value = "修改")
    @PreAuthorize("hasAuthority('sys:menu:edit')")
    @ApiOperation("修改")
    @PostMapping("/edit")
    public void editMenu(@RequestBody SysMenuEditParamModel paramModel){
        SysMenuEntity sysMenuEntity = sysMenuService.getById(paramModel.getId());
        if(sysMenuEntity == null){
            throw ApiException.getInstance("数据不存在,请刷新重试");
        }
        sysMenuEntity.setSysMenuEntity(paramModel);
        String levelStr = sysMenuService.getMenuLevelStr(paramModel.getPid(),sysMenuEntity.getId());
        sysMenuEntity.setLevelStr(levelStr);
        sysMenuService.saveOrUpdate(sysMenuEntity);
    }

    @Logging(tags = "菜单管理",value = "删除")
    @PreAuthorize("hasAuthority('sys:menu:delByIds')")
    @ApiOperation("删除")
    @DeleteMapping("/delByIds/{ids}")
    public void delById(@PathVariable String[] ids){
        sysMenuService.removeBatchByIds(Arrays.asList(ids));
    }


    @ApiOperation("查询用户树形菜单")
    @GetMapping("/findUserMenuByTree")
    public Object findUserMenuByTree() {
        List<MenuAddOrEditModel> sysMenuList = sysMenuService.findUserMenuByTree(SecurityUtil.getUserId());
        return sysMenuList;
    }

    @ApiOperation("查询选项框树形数据")
    @GetMapping("/findSelectByTree")
    public Object findSelectByTree(@RequestParam(defaultValue = "false",required = true)Boolean isAll){
        List<SysMenuEntity> menuAllList = sysMenuService.<MenuAddOrEditModel>list();
        List<MenuAddOrEditModel> list = BeanUtil.copyToList(menuAllList, MenuAddOrEditModel.class);
        List<MenuAddOrEditModel> caidanList = list.stream().filter(item->"0".equals(item.getPid())).sorted(Comparator.comparing(MenuAddOrEditModel::getSort)).collect(Collectors.toList());
        for (MenuAddOrEditModel caidanModel : caidanList) {
            List<MenuAddOrEditModel> zicaidanList = list.stream().filter(item->caidanModel.getId().equals(item.getPid())).sorted(Comparator.comparing(MenuAddOrEditModel::getSort)).collect(Collectors.toList());
            if(isAll){
                for (MenuAddOrEditModel zicaidanModel : zicaidanList) {
                    List<MenuAddOrEditModel> gongnengList = list.stream().filter(item->zicaidanModel.getId().equals(item.getPid())).sorted(Comparator.comparing(MenuAddOrEditModel::getSort)).collect(Collectors.toList());
                    zicaidanModel.setChildren(gongnengList);
                }
            }
            caidanModel.setChildren(zicaidanList);
        }
        MenuAddOrEditModel sysMenuModel = new MenuAddOrEditModel();
        sysMenuModel.setId("0");
        sysMenuModel.setPid("0");
        sysMenuModel.setName("根目录");
        sysMenuModel.setType("CAIDAN");
        sysMenuModel.setChildren(caidanList);
        return Arrays.asList(sysMenuModel);
    }

    @ApiOperation("查询用户权限")
    @GetMapping("/findAllPerByUserId")
    public Object findAllPerByUserId() {
        List<String> permissionList = sysMenuService.findAllPerByUserId(getUserId());
        return permissionList;
    }

}
